<template>
  <div class="indicator-management">
    <div class="header-section">
      <div class="left-actions">
        <el-button type="primary" @click="handleCreateIndicator">
          <i class="el-icon-plus"></i>
          新建指标
        </el-button>

        <el-button type="primary" @click="handleBatchExecute">
          <i class="el-icon-refresh"></i>
          批量执行
        </el-button>
      </div>

      <div class="right-filters">
        <div class="filter-item">
          <label>年</label>
          <el-select
            v-model="filters.year"
            placeholder="请选择年份"
            @change="handleYearChange"
            clearable
          >
            <el-option
              v-for="year in yearOptions"
              :key="year"
              :label="year"
              :value="year"
            />
          </el-select>
        </div>

        <div class="filter-item">
          <label>指标</label>
          <el-select
            v-model="filters.type"
            placeholder="请选择指标类型"
            @change="handleSearch"
            clearable
          >
            <el-option label="全市通用" value="1" />
            <el-option label="区县特色" value="2" />
          </el-select>
        </div>

        <div class="filter-item">
          <label>一级视角</label>
          <el-input
            v-model="filters.firstView"
            placeholder="请输入一级视角"
            @input="handleSearch"
            clearable
          />
        </div>

        <div class="filter-item">
          <label>二级视角</label>
          <el-input
            v-model="filters.secondView"
            placeholder="请输入二级视角"
            @input="handleSearch"
            clearable
          />
        </div>

        <div class="filter-item">
          <label>搜索指标</label>
          <el-input
            v-model="filters.indexName"
            placeholder="请输入搜索指标"
            @input="handleSearch"
            prefix-icon="el-icon-search"
            clearable
          />
        </div>
      </div>
    </div>

    <div class="table-section">
      <el-table
        v-loading="loading"
        :data="tableData"
        stripe
        style="width: 100%"
        height="100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="55"
        ></el-table-column>
        <el-table-column prop="firstView" label="一级视角" min-width="120">
        </el-table-column>
        <el-table-column prop="secondView" label="二级视角" min-width="120">
        </el-table-column>
        <el-table-column prop="indexName" label="指标名称" min-width="150">
        </el-table-column>
        <el-table-column prop="unit" label="指标单位" min-width="100">
        </el-table-column>
        <el-table-column prop="indexValue" label="指标值" min-width="120">
        </el-table-column>
        <el-table-column prop="coreRun" label="查询语句" min-width="300">
          <template #default="{ row }">
            <div class="table-cell-content" :title="row.coreRun">
              {{ row.coreRun }}
              <div>
                <el-button type="text" size="small" @click="handleCoreRun(row)">
                  {{ row.coreRun ? '编辑' : '添加' }}
                </el-button>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="departField" label="分区字段" min-width="120">
        </el-table-column>
        <el-table-column
          prop="mapUrl"
          label="地图链接"
          min-width="300"
        >
          <template #default="{ row }">
            <div class="table-cell-content">
              <div v-if="row.mapDarknessUrl || row.mapTintUrl">
                <div v-if="row.mapDarknessUrl">
                  <span>深色：</span>
                  <span>{{ row.mapDarknessUrl }}</span>
                </div>
                <div v-if="row.mapTintUrl">
                  <span>浅色：</span>
                  <span>{{ row.mapTintUrl }}</span>
                </div>
                <div v-else>-</div>
                <div>
                  <el-button type="text" size="small" @click="handleEditMap(row)">
                    编辑
                  </el-button>
                </div>
              </div>
              <div v-else>
                <el-button type="text" size="small" @click="handleEditMap(row)">
                  添加
                </el-button>  
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="fieldJson" label="字段顺序" min-width="150">
        </el-table-column>
        <el-table-column prop="commonJudgeList" label="评价标准" min-width="200">
          <template #default="{ row }">
            <div class="judge-type-cell">
              <div class="judge-content">
                {{ renderJudgeList(row.commonJudgeList) }}
              </div>
              <div class="judge-actions">
                <el-button type="text" size="small" @click="handleJudgeType(row)">
                  {{ row.commonJudgeList && row.commonJudgeList.length > 0 ? '编辑' : '添加' }}
                </el-button>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="judgeResult" label="评价结果" min-width="500">
        </el-table-column>
        <el-table-column prop="indexDefine" label="指标定义" min-width="300">
        </el-table-column>
        <el-table-column prop="indexResult" label="指标结论" min-width="200">
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="text" size="small" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="text" size="small" @click="handleCopy(row)">
              复制
            </el-button>

            <el-button type="text" style="color: red" size="small" @click="handleDelete(row)">
              删除
            </el-button>
            <el-button type="text" size="small" @click="handleLog(row)">
              日志
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-wrapper">
        <el-pagination
          :current-page="pagination.currentPage"
          :page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 新建/编辑指标弹窗 -->
    <IndicatorDialog
      :visible.sync="dialogVisible"
      :is-edit="isEditMode"
      :year-options="yearOptions"
      :edit-data="currentEditData"
      @submit="handleDialogSubmit"
    />

    <!-- 评价标准编辑弹窗 -->
    <JudgeTypeDialog
      :visible.sync="judgeDialogVisible"
      :row-data="currentJudgeData"
      @submit="handleJudgeSubmit"
    />

    <!-- 操作日志弹窗 -->
    <LogDialog
      :visible.sync="logDialogVisible"
      :index-id="currentLogIndexId"
    />

    <!-- 查询语句管理弹窗 -->
    <CoreRunDialog
      :visible.sync="coreRunDialogVisible"
      :row-data="currentCoreRunData"
      @submit="handleCoreRunSubmit"
    />

    <!-- 地图服务配置弹窗 -->
    <MapConfigDialog
      :visible.sync="mapConfigDialogVisible"
      :row-data="currentMapConfigData"
      @submit="handleMapConfigSubmit"
    />
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { Message, MessageBox } from 'element-ui'
import {
  getIndicatorYear,
  getIndicatorList,
  addOrUpdateIndicator,
  deleteIndicator,
  copyIndicator,
  addJudge,
  addLayerFieldsByLayerName,
  executeMutiSql
} from '@/api/screen-management/indicator-management'
import IndicatorDialog from './components/IndicatorDialog.vue'
import JudgeTypeDialog from './components/JudgeTypeDialog.vue'
import LogDialog from './components/LogDialog.vue'
import CoreRunDialog from './components/CoreRunDialog.vue'
import MapConfigDialog from './components/MapConfigDialog.vue'

interface Filters {
  year: string
  type: string
  firstView: string
  secondView: string
  indexName: string
}

interface Pagination {
  currentPage: number
  pageSize: number
  total: number
}

interface TableRow {
  firstView: string
  secondView: string
  indexName: string
  unit: string
  indexValue: string
  coreRun: string
  coreRunDataSource?: string
  departField: string
  mapUrl: string
  fieldJson: string
  judgeType: string
  judgeResult: string
  indexDefine: string
  indexResult: string
  pkid: string
  commonJudgeList?: any[]
}

const loading = ref<boolean>(false)
const tableData = ref<TableRow[]>([])
const yearOptions = ref<string[]>([])

const dialogVisible = ref<boolean>(false)
const isEditMode = ref<boolean>(false)
const currentEditData = ref<Partial<TableRow>>({})

const judgeDialogVisible = ref<boolean>(false)
const currentJudgeData = ref<Partial<TableRow>>({})

const logDialogVisible = ref<boolean>(false)
const currentLogIndexId = ref<string>('')

const coreRunDialogVisible = ref<boolean>(false)
const currentCoreRunData = ref<Partial<TableRow>>({})

const mapConfigDialogVisible = ref<boolean>(false)
const currentMapConfigData = ref<Partial<TableRow>>({})

const mutiSelected = ref<any[]>([])


const filters = reactive<Filters>({
  year: '',
  type: '',
  firstView: '',
  secondView: '',
  indexName: '',
})

const pagination = reactive<Pagination>({
  currentPage: 1,
  pageSize: 20,
  total: 0,
})

const renderJudgeList = (judgeList: any[]): string => {
  if (!judgeList || judgeList.length === 0) {
    return ''
  }
  
  const getJudgeTypeText = (judgeType: string): string => {
    const typeMap: Record<string, string> = {
      'between': '区间型',
      'top': '目标型',
      'bottom': '底线型',
      'normal': '普查型'
    }
    return typeMap[judgeType] || judgeType
  }
  
  const firstJudge = judgeList[0]
  const judgeTypeText = getJudgeTypeText(firstJudge.judgeType)
  
  const judgeItems = judgeList.map((judge: any) => {
    let rangeText = ''
    
    if (judge.judgeType === 'between') {
      rangeText = `${judge.judgeMinValue}-${judge.judgeMaxValue}`
    } else if (judge.judgeType === 'top') {
      rangeText = `>=${judge.judgeMinValue}`
    } else if (judge.judgeType === 'bottom') {
      rangeText = `<${judge.judgeMaxValue}`
    }
    
    return rangeText ? `${rangeText} ${judge.judgeName}` : judge.judgeName
  }).join('\n')
  
  return `${judgeTypeText}\n${judgeItems}`
}


const fetchYearOptions = async (): Promise<void> => {
  try {
    const response = await getIndicatorYear()
    if (response.success) {
      yearOptions.value = response.data || []
    } else {
      yearOptions.value = []
    }
  } catch (error) {
    console.error('Failed to fetch year options:', error)
    yearOptions.value = []
  }
}

const fetchTableData = async (): Promise<void> => {
  loading.value = true
  try {
    const params: any = {
      pageIndex: pagination.currentPage,
      pageSize: pagination.pageSize,
    }

    if (filters.year) params.year = filters.year
    if (filters.type) params.type = filters.type
    if (filters.firstView) params.firstView = filters.firstView
    if (filters.secondView) params.secondView = filters.secondView
    if (filters.indexName) params.indexName = filters.indexName

    const response = await getIndicatorList(params)

    if (response.success) {
      tableData.value = response.data.list || []
      pagination.total = response.data.count || 0
    } else {
      tableData.value = []
      pagination.total = 0
    }
  } catch (error) {
    console.error('Failed to fetch table data:', error)
    tableData.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

const handleCreateIndicator = (): void => {
  isEditMode.value = false
  currentEditData.value = {}
  dialogVisible.value = true
}

const handleYearChange = (): void => {
  pagination.currentPage = 1
  fetchTableData()
}

const handleSearch = (): void => {
  pagination.currentPage = 1
  fetchTableData()
}

const handleCopy = async (row: TableRow): Promise<void> => {
  const response = await copyIndicator({pkid: row.pkid})
  if (response.success) {
    Message.success('复制成功')
    await fetchTableData()
  }
}

const handleJudgeType = (row: TableRow): void => {
  currentJudgeData.value = { ...row }
  judgeDialogVisible.value = true
}

const handleJudgeSubmit = async (formData: any): Promise<void> => {
  try {
    const response = await addJudge(formData)
    if (response.success) {
      Message.success('评价标准保存成功')
      await fetchTableData()
    }
  } catch (error) {
    console.error('Failed to submit judge data:', error)
  }
}

const handleEdit = (row: TableRow): void => {
  isEditMode.value = true
  currentEditData.value = { ...row }
  dialogVisible.value = true
}

const handleDialogSubmit = async (formData: any): Promise<void> => {
  try {
    let response
    if (isEditMode.value) {
      response = await addOrUpdateIndicator({...formData, pkid: currentEditData.value.pkid})
    } else {
      response = await addOrUpdateIndicator(formData)
    }
    
    if (response.success) {
      Message.success(isEditMode.value ? '更新指标成功' : '创建指标成功')
      dialogVisible.value = false
      await fetchTableData()
    }
  } catch (error) {
    console.error('Failed to submit indicator:', error)
  }
}

const handleDelete = async (row: TableRow): Promise<void> => {
  try {
    await MessageBox.confirm(
      `确定要删除指标"${row.indexName}"吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    const response = await deleteIndicator({pkid: row.pkid})
    
    if (response.success) {
      Message.success('删除成功')
      fetchTableData()
    }
  } catch (error: any) {
    if (error === 'cancel') {
      return
    }
  }
}

const handleSizeChange = (size: number): void => {
  pagination.pageSize = size
  pagination.currentPage = 1
  fetchTableData()
}

const handleCurrentChange = (page: number): void => {
  pagination.currentPage = page
  fetchTableData()
}

const handleLog = (row: TableRow): void => {
  currentLogIndexId.value = row.pkid || ''
  logDialogVisible.value = true
}

const handleCoreRun = (row: TableRow): void => {
  currentCoreRunData.value = { ...row }
  coreRunDialogVisible.value = true
}

const handleCoreRunSubmit = async (): Promise<void> => {
  // 刷新表格数据以显示更新后的查询语句
  await fetchTableData()
}

const handleEditMap = (row: TableRow): void => {
  currentMapConfigData.value = { ...row }
  mapConfigDialogVisible.value = true
}

const handleMapConfigSubmit = async (configData: any): Promise<void> => {
  try {
    const response = await addLayerFieldsByLayerName(configData)
    if (response.success) {
      await fetchTableData()
      Message.success('地图配置保存成功')
    } else {
      Message.error('保存失败')
    }
  } catch (error) {
    console.error('Failed to save map config:', error)
    Message.error('保存失败')
  }
}

const handleSelectionChange = (selects: any)=> {
  mutiSelected.value = selects
}

const handleBatchExecute = ()=> {
  const params = {
    pkid: ''
  }
  if (mutiSelected.value.length > 0) {
    params.pkid = mutiSelected.value.map((item: any)=> item.pkid).join(',')
  }
  loading.value = true
  executeMutiSql(params).then((res: any)=> {
    if (res.data) {
      Message.success(res.data)
      fetchTableData()
    } else {
      // 使用 dangerouslyUseHTMLString 选项来支持 HTML 内容
      const msg = res.message.replace(/\n/g, '<br/>')
      Message.error({
        message: msg,
        dangerouslyUseHTMLString: true,
        duration: 5000
      })
    }
    loading.value = false
  }).catch(()=> {
    loading.value = false
  })
}

onMounted(() => {
  fetchYearOptions()
  fetchTableData()
})
</script>

<style scoped lang="scss">
.indicator-management {
  padding: 20px;
  background: #fff;
  height: calc(100vh - 130px);
  display: flex;
  flex-direction: column;

  .header-section {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 20px;
    padding-bottom: 20px;
    border-bottom: 1px solid #ebeef5;
    flex-shrink: 0;

    .left-actions {
      display: flex;
      align-items: center;
    }

    .right-filters {
      display: flex;
      gap: 20px;
      align-items: center;
      flex-wrap: wrap;

      .filter-item {
        display: flex;
        align-items: center;
        gap: 8px;

        .el-select,
        .el-input {
          width: 200px;
        }
      }
    }
  }

  .table-section {
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow: hidden;

    .el-table {
      flex: 1;
    }

    .pagination-wrapper {
      display: flex;
      justify-content: flex-end;
      margin-top: 20px;
      padding-top: 15px;
      border-top: 1px solid #ebeef5;
      flex-shrink: 0;
    }

    // 地图链接样式
    .map-link {
      color: #409eff;
      text-decoration: none;

      &:hover {
        color: #66b1ff;
        text-decoration: underline;
      }
    }

    // 评价标准单元格样式
    .judge-type-cell {
      .judge-content {
        white-space: pre-line;
        line-height: 1.4;
        margin-bottom: 4px;
        font-size: 13px;
      }
      
      .judge-actions {
        margin-top: 4px;
      }
    }
  }
}

@media (max-width: 1400px) {
  .indicator-management {
    .header-section {
      flex-direction: column;
      gap: 20px;

      .right-filters {
        width: 100%;
        justify-content: flex-start;

        .filter-item {
          .el-select,
          .el-input {
            width: 140px;
          }
        }
      }
    }
  }
}

@media (max-width: 768px) {
  .indicator-management {
    padding: 16px;

    .header-section {
      .right-filters {
        flex-direction: column;
        align-items: flex-start;
        gap: 12px;

        .filter-item {
          width: 100%;

          .el-select,
          .el-input {
            width: 100%;
          }
        }
      }
    }
  }
}

.el-message__content {
  white-space: pre-line !important;
}
</style>
